/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.csp.sentinel.dashboard.rule.appollo;


import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.RuleEntity;
import com.alibaba.csp.sentinel.dashboard.discovery.AppInfo;
import com.alibaba.csp.sentinel.dashboard.rule.AbstractDynamicRuleProvider;
import com.alibaba.csp.sentinel.dashboard.rule.convert.Converter;
import com.alibaba.csp.sentinel.dashboard.rule.util.ConfigIdUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.ctrip.framework.apollo.openapi.client.ApolloOpenApiClient;
import com.ctrip.framework.apollo.openapi.dto.OpenItemDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenNamespaceDTO;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: shaozeming
 * @date: 2022/8/8 15:24
 * @description:
 **/
public class FlowRuleApolloProvider extends AbstractDynamicRuleProvider {


    private ApolloOpenApiClient apolloOpenApiClient;

    private ApolloConfig apolloConfig;

    public FlowRuleApolloProvider(ApolloOpenApiClient apolloOpenApiClient,ApolloConfig apolloConfig){
        this.apolloOpenApiClient =apolloOpenApiClient;
        this.apolloConfig =apolloConfig;
    }

    @Override
    protected List<RuleEntity> getPrivateRules(AppInfo appInfo, Class<?> clz) throws Exception {
        return Converter.decode(appInfo,getRuleConfig(ConfigIdUtil.getKey(clz)),clz);
    }

    @Override
    protected List<RuleEntity> getDefaultRules(AppInfo appInfo, Class<?> clz) throws Exception {
        String defaultKey = ConfigIdUtil.getDefaultKey(clz);
        if(defaultKey ==null ||defaultKey.length() ==0){
            return new ArrayList<>();
        }
        return Converter.decode(appInfo,getRuleConfig(defaultKey),clz);
    }


    private String getRuleConfig(String flowDataId){
        OpenNamespaceDTO openNamespaceDTO = apolloOpenApiClient.getNamespace(apolloConfig.getAppId(), apolloConfig.getEnv(), apolloConfig.getClusterName(), apolloConfig.getNamespaceName());
        String rules = openNamespaceDTO
                .getItems()
                .stream()
                .filter(p -> p.getKey().equals(flowDataId))
                .map(OpenItemDTO::getValue)
                .findFirst()
                .orElse("");

        if (StringUtil.isEmpty(rules)) {
            return null;
        }
        return rules;
    }


}
